//
//  taskViewController.m
//  BackgroundTaskSample
//  后台任务
//  app后台运行时间为10分钟，此时可以执行一些重要的任务。
//  当用户锁屏后，此时后台任务是被暂停的，设备在特定时间进行系统应用的操作被唤醒（比如检查邮件或者接到来电等）时，被暂停的任务将一起进行。
//  Created by moliya on 16/4/23.
//  Copyright © 2016年 Wanquan Network Technology. All rights reserved.
//

#import "taskViewController.h"

@interface taskViewController ()
@property (weak, nonatomic) IBOutlet UILabel *taskStateShowLabel;
@property (copy, nonatomic) NSString *taskStateDescription;

@end

@implementation taskViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - Background Task
- (void)executeBackgroundTask {
    UIApplication *application = [UIApplication sharedApplication];
    //执行异步任务
    //任务的结束分两种情况：后台任务超时和后台任务完成，此时则需要调用结束后台任务的方法
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //启动后台任务
        //UIBackgroundTaskIdentifier：后台任务标识
        __block UIBackgroundTaskIdentifier task = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
            _taskStateDescription = @"后台任务执行超时";
            //任务超时回调，如果超时则结束该任务
            [application endBackgroundTask:task];
            task = UIBackgroundTaskInvalid;
        }];
        
        //执行的任务实现
        //TODO
        NSLog(@"后台任务执行中");
        _taskStateDescription = @"后台任务执行完成";
        
        //结束后台任务
        [application endBackgroundTask:task];
        task = UIBackgroundTaskInvalid;
    });
}

#pragma mark - Update Label Description
- (void)updateTaskStateLabel {
    if (_taskStateDescription) {
        _taskStateShowLabel.text = _taskStateDescription;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
